import type {
  Comment,
  Novel,
  NovelChapter,
} from '@/api/types/novel'
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import {
  addFavorite,
  addReadingHistory,
  checkFavorite,
  createComment,
  getChapterList,
  getComments,
  getNovelDetail,
  getReadingProgress,
  getRecommendedNovels,
  likeComment,
  removeFavorite,
  unlikeComment,
} from '@/api/novel'

// 缓存时间常量（毫秒）
const CACHE_DURATION = {
  NOVEL_DETAIL: 30 * 60 * 1000, // 30分钟
  CHAPTER_LIST: 60 * 60 * 1000, // 1小时
  COMMENTS: 15 * 60 * 1000, // 15分钟
  RECOMMENDATIONS: 60 * 60 * 1000, // 1小时
}

export const useNovelDetailStore = defineStore(
  'novelDetail',
  () => {
    // ==================== 状态定义 ====================

    // 小说基本信息
    const novel = ref<Novel | null>(null)
    const novelLoading = ref(false)
    const novelError = ref<string | null>(null)

    // 章节列表
    const chapters = ref<NovelChapter[]>([])
    const chaptersLoading = ref(false)
    const chaptersError = ref<string | null>(null)
    const currentChapterId = ref<number | null>(null)

    // 评论列表
    const comments = ref<Comment[]>([])
    const commentsLoading = ref(false)
    const commentsError = ref<string | null>(null)
    const commentsPage = ref(1)
    const commentsHasMore = ref(true)

    // 推荐小说
    const recommendations = ref<Novel[]>([])
    const recommendationsLoading = ref(false)
    const recommendationsError = ref<string | null>(null)

    // 用户交互状态
    const isFavorited = ref(false)
    const favoriteLoading = ref(false)
    const readingProgress = ref(0) // 阅读进度百分比
    const lastReadChapter = ref<number | null>(null)

    // 页面状态
    const activeTab = ref('intro')
    const refreshing = ref(false)

    // 缓存时间戳
    const cacheTimestamps = ref<Record<string, number>>({
      novel: 0,
      chapters: 0,
      comments: 0,
      recommendations: 0,
    })

    // ==================== 计算属性 ====================

    // 格式化字数显示
    const formattedWordCount = computed(() => {
      if (!novel.value?.wordCount)
        return '0字'
      if (novel.value.wordCount >= 10000) {
        return `${(novel.value.wordCount / 10000).toFixed(1)}万字`
      }
      return `${novel.value.wordCount}字`
    })

    // 格式化阅读量显示
    const formattedViewCount = computed(() => {
      if (!novel.value?.readCount)
        return '0'
      if (novel.value.readCount >= 10000) {
        return `${(novel.value.readCount / 10000).toFixed(1)}万`
      }
      return novel.value.readCount.toString()
    })

    // 已读章节数
    const readChaptersCount = computed(() => {
      return chapters.value.filter((ch) => {
        // 这里应该根据阅读历史来判断，暂时用章节ID小于当前章节
        return currentChapterId.value && ch.id <= currentChapterId.value
      }).length
    })

    // 阅读进度百分比
    const progressPercentage = computed(() => {
      if (!chapters.value.length)
        return 0
      return Math.round((readChaptersCount.value / chapters.value.length) * 100)
    })

    // 小说状态标签
    const statusText = computed(() => {
      if (!novel.value)
        return ''
      return novel.value.status === 1 ? '连载中' : '已完结'
    })

    // 评分显示
    const ratingScore = computed(() => {
      if (!novel.value?.ratingScore)
        return '0.0'
      const score = Number(novel.value.ratingScore)
      return Number.isNaN(score) ? '0.0' : score.toFixed(1)
    })

    // 检查章节是否已读
    const isChapterRead = (chapterId: number) => {
      return currentChapterId.value && chapterId <= currentChapterId.value
    }

    // ==================== 缓存工具方法 ====================

    // 检查缓存是否过期
    const isCacheExpired = (key: string, duration: number): boolean => {
      const timestamp = cacheTimestamps.value[key] || 0
      return Date.now() - timestamp > duration
    }

    // 更新缓存时间戳
    const updateCacheTimestamp = (key: string): void => {
      cacheTimestamps.value[key] = Date.now()
    }

    // 清除特定缓存
    const clearCache = (key: string): void => {
      cacheTimestamps.value[key] = 0
    }

    // ==================== API 调用方法 ====================

    /**
     * 获取小说详情
     */
    const fetchNovelDetail = async (id: number, forceRefresh = false) => {
      // 检查缓存
      if (!forceRefresh
        && novel.value?.id === id
        && !isCacheExpired('novel', CACHE_DURATION.NOVEL_DETAIL)) {
        return novel.value
      }

      try {
        novelLoading.value = true
        novelError.value = null

        const data = await getNovelDetail(id)
        novel.value = data

        // 从API响应中直接获取收藏状态（如果后端返回了）
        isFavorited.value = data.isFavorited || false
        console.log('从API响应中获取收藏状态:', isFavorited.value)

        updateCacheTimestamp('novel')

        return data
      }
      catch (error: any) {
        novelError.value = error.message || '获取小说详情失败'
        throw error
      }
      finally {
        novelLoading.value = false
      }
    }

    /**
     * 获取章节列表
     */
    const fetchChapterList = async (novelId: number, forceRefresh = false) => {
      // 检查缓存
      if (!forceRefresh
        && chapters.value.length > 0
        && !isCacheExpired('chapters', CACHE_DURATION.CHAPTER_LIST)) {
        return chapters.value
      }

      try {
        chaptersLoading.value = true
        chaptersError.value = null

        const response = await getChapterList(novelId, { limit: 1000 }) // 获取所有章节
        chapters.value = response.items
        updateCacheTimestamp('chapters')

        return response.items
      }
      catch (error: any) {
        chaptersError.value = error.message || '获取章节列表失败'
        throw error
      }
      finally {
        chaptersLoading.value = false
      }
    }

    /**
     * 获取评论列表
     */
    const fetchComments = async (novelId: number, page = 1, reset = false) => {
      try {
        commentsLoading.value = true
        commentsError.value = null

        const response = await getComments({
          novelId,
          page,
          limit: 20,
          sortBy: 'createdAt',
          sortOrder: 'desc',
        })

        if (reset || page === 1) {
          comments.value = response.items
        }
        else {
          comments.value.push(...response.items)
        }

        commentsPage.value = page
        commentsHasMore.value = response.meta.hasNext
        updateCacheTimestamp('comments')

        return response.items
      }
      catch (error: any) {
        commentsError.value = error.message || '获取评论失败'
        throw error
      }
      finally {
        commentsLoading.value = false
      }
    }

    /**
     * 获取推荐小说
     */
    const fetchRecommendations = async (novelId: number, forceRefresh = false) => {
      // 检查缓存
      if (!forceRefresh
        && recommendations.value.length > 0
        && !isCacheExpired('recommendations', CACHE_DURATION.RECOMMENDATIONS)) {
        return recommendations.value
      }

      try {
        recommendationsLoading.value = true
        recommendationsError.value = null

        const data = await getRecommendedNovels({ limit: 6 })
        recommendations.value = data
        updateCacheTimestamp('recommendations')

        return data
      }
      catch (error: any) {
        recommendationsError.value = error.message || '获取推荐小说失败'
        throw error
      }
      finally {
        recommendationsLoading.value = false
      }
    }

    // ==================== 用户交互方法 ====================

    /**
     * 检查收藏状态
     */
    const checkFavoriteStatus = async (novelId: number) => {
      try {
        const response = await checkFavorite(novelId)
        isFavorited.value = response.isFavorited
      }
      catch (error) {
        // 收藏状态检查失败不影响主要功能
        console.warn('检查收藏状态失败:', error)
      }
    }

    /**
     * 加载阅读进度
     */
    const loadReadingProgress = async (novelId: number) => {
      try {
        const response = await getReadingProgress(novelId)
        readingProgress.value = response.progress

        // 如果有进度，计算当前应该阅读的章节
        if (response.progress > 0 && chapters.value.length > 0) {
          const targetChapterIndex = Math.floor(
            (response.progress / 100) * chapters.value.length,
          )
          currentChapterId.value = chapters.value[targetChapterIndex]?.id || null
          lastReadChapter.value = currentChapterId.value
        }
      }
      catch (error) {
        // 阅读进度加载失败不影响主要功能
        console.warn('加载阅读进度失败:', error)
      }
    }

    /**
     * 加载小说完整数据
     */
    const loadNovelData = async (id: number, forceRefresh = false) => {
      try {
        // 并行加载主要数据
        const [novelData] = await Promise.all([
          fetchNovelDetail(id, forceRefresh),
          fetchChapterList(id, forceRefresh),
          fetchRecommendations(id, forceRefresh),
        ])

        // 只加载阅读进度（收藏状态已在小说详情API中返回）
        await Promise.all([
          loadReadingProgress(id),
        ])

        // 加载评论
        await fetchComments(id, 1, true)

        return novelData
      }
      catch (error) {
        console.error('加载小说数据失败:', error)
        throw error
      }
    }

    // ==================== 用户交互方法 ====================

    /**
     * 切换收藏状态
     */
    const toggleFavorite = async (novelId: number, bookshelfId?: number) => {
      if (favoriteLoading.value)
        return

      try {
        favoriteLoading.value = true

        if (isFavorited.value) {
          await removeFavorite(novelId)
          isFavorited.value = false
          uni.showToast({ title: '已取消收藏', icon: 'success' })
        }
        else {
          await addFavorite({ novelId, bookshelfId })
          isFavorited.value = true
          uni.showToast({ title: '已添加到书架', icon: 'success' })
        }
      }
      catch (error: any) {
        uni.showToast({
          title: error.message || '操作失败',
          icon: 'none',
        })
        throw error
      }
      finally {
        favoriteLoading.value = false
      }
    }

    /**
     * 更新阅读进度
     */
    const updateReadingProgress = async (novelId: number, chapterId: number, progress?: string) => {
      try {
        await addReadingHistory({
          novelId,
          chapterId,
          readProgress: progress || `${progressPercentage.value}%`,
        })

        currentChapterId.value = chapterId
        lastReadChapter.value = chapterId

        // 重新计算进度百分比
        if (chapters.value.length > 0) {
          const chapterIndex = chapters.value.findIndex(ch => ch.id === chapterId)
          if (chapterIndex !== -1) {
            readingProgress.value = Math.round(((chapterIndex + 1) / chapters.value.length) * 100)
          }
        }
      }
      catch (error) {
        console.warn('更新阅读进度失败:', error)
      }
    }

    /**
     * 发表评论
     */
    const submitComment = async (novelId: number, content: string, rating?: number) => {
      try {
        const newComment = await createComment({
          novelId,
          content,
          chapterId: undefined, // 小说详情页的评论不关联具体章节
        })

        // 将新评论添加到列表开头
        comments.value.unshift(newComment)

        return newComment
      }
      catch (error: any) {
        uni.showToast({
          title: error.message || '发表评论失败',
          icon: 'none',
        })
        throw error
      }
    }

    /**
     * 点赞/取消点赞评论
     */
    const toggleCommentLike = async (commentId: number) => {
      const comment = comments.value.find(c => c.id === commentId)
      if (!comment)
        return

      try {
        if (comment.isLiked) {
          await unlikeComment(commentId)
          comment.likeCount--
          comment.isLiked = false
        }
        else {
          await likeComment(commentId)
          comment.likeCount++
          comment.isLiked = true
        }
      }
      catch (error: any) {
        uni.showToast({
          title: error.message || '操作失败',
          icon: 'none',
        })
        throw error
      }
    }

    // ==================== 页面状态方法 ====================

    /**
     * 下拉刷新
     */
    const refresh = async (novelId: number) => {
      try {
        refreshing.value = true

        // 清除所有缓存
        Object.keys(cacheTimestamps.value).forEach((key) => {
          clearCache(key)
        })

        // 重新加载数据
        await loadNovelData(novelId, true)

        uni.showToast({ title: '刷新成功', icon: 'success' })
      }
      catch (error) {
        uni.showToast({ title: '刷新失败', icon: 'none' })
      }
      finally {
        refreshing.value = false
      }
    }

    /**
     * 重置状态
     */
    const reset = () => {
      novel.value = null
      chapters.value = []
      comments.value = []
      recommendations.value = []
      isFavorited.value = false
      readingProgress.value = 0
      currentChapterId.value = null
      lastReadChapter.value = null
      activeTab.value = 'intro'

      // 重置错误状态
      novelError.value = null
      chaptersError.value = null
      commentsError.value = null
      recommendationsError.value = null

      // 重置加载状态
      novelLoading.value = false
      chaptersLoading.value = false
      commentsLoading.value = false
      recommendationsLoading.value = false
      favoriteLoading.value = false
      refreshing.value = false
    }

    // ==================== 返回 ====================

    return {
      // 状态
      novel,
      chapters,
      comments,
      recommendations,
      isFavorited,
      readingProgress,
      currentChapterId,
      lastReadChapter,
      activeTab,

      // 加载状态
      novelLoading,
      chaptersLoading,
      commentsLoading,
      recommendationsLoading,
      favoriteLoading,
      refreshing,

      // 错误状态
      novelError,
      chaptersError,
      commentsError,
      recommendationsError,

      // 分页状态
      commentsPage,
      commentsHasMore,

      // 计算属性
      formattedWordCount,
      formattedViewCount,
      readChaptersCount,
      progressPercentage,
      statusText,
      ratingScore,

      // 方法
      fetchNovelDetail,
      fetchChapterList,
      fetchComments,
      fetchRecommendations,
      loadNovelData,
      toggleFavorite,
      updateReadingProgress,
      submitComment,
      toggleCommentLike,
      refresh,
      reset,
      checkFavoriteStatus,
      loadReadingProgress,
      isChapterRead,

      // 缓存方法
      clearCache,
      isCacheExpired,
    }
  },
  {
    persist: {
      key: 'novel-detail-store',
      storage: {
        getItem: uni.getStorageSync,
        setItem: uni.setStorageSync,
      },
      paths: [
        'novel',
        'chapters',
        'recommendations',
        'isFavorited',
        'readingProgress',
        'currentChapterId',
        'lastReadChapter',
        'cacheTimestamps',
      ],
    },
  },
)
